package cn.liuyi.weiyi;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.pku.tools.Base64Coder;
import cn.edu.pku.tools.BitmapHelper;
import cn.edu.pku.tools.FileHelper;
import cn.edu.pku.tools.SharedPreferencesHelper;
import cn.edu.pku.tools.YJRApplication;
import cn.edu.pku.tools.YJRHttpClient;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.LayoutParams;
import com.actionbarsherlock.app.SherlockActivity;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

public class AccountActivity extends SherlockActivity
  implements View.OnClickListener
{
  ActionBar actionBar;
  TextView change_head_tv;
  Context context;
  FileHelper fileHelper;
  RelativeLayout gender_rl, change_head_rl, phone_rl, pwd_rl;
  ImageView head_imv;
  Bitmap header_bitmap;
  SharedPreferencesHelper helper;
  LayoutInflater inflater;
  JSONObject jsonInfo;
  Button logout_btn;
  String logout_url = "http://115.28.222.1/yijiaren/user/logout.action";
  Handler mHandler;
  String name = "向北向南61";
  RelativeLayout name_rl;
  TextView name_show_tv;
  LinearLayout page_ll;
  String phone_num = "15201317795", new_phone;
  TextView phone_number_show_tv;
  String response, head_path;
  View title_bar;
  
  static final int name_edit_code = 4;
  
  DisplayImageOptions options;
  protected ImageLoader imageLoader = ImageLoader.getInstance();
  
  private void ShowPickDialog() {  
      new AlertDialog.Builder(this)  
              .setTitle("设置头像")  
              .setNegativeButton("相册", new DialogInterface.OnClickListener() {  
                  public void onClick(DialogInterface dialog, int which) {  
                      dialog.dismiss();  
                      /**  
                       * 刚开始，我自己也不知道ACTION_PICK是干嘛的，后来直接看Intent源码，  
                       * 可以发现里面很多东西，Intent是个很强大的东西，大家一定仔细阅读下  
                       */ 
                      Intent intent = new Intent(Intent.ACTION_PICK, null);  
                        
                      /**  
                       * 下面这句话，与其它方式写是一样的效果，如果：  
                       * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
                       * intent.setType(""image/*");设置数据类型  
                       * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"  
                       * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？  
                       */ 
                      intent.setDataAndType(  
                              MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
                              "image/*");  
                      startActivityForResult(intent, 1);  

                  }  
              })  
              .setPositiveButton("拍照", new DialogInterface.OnClickListener() {  
                  public void onClick(DialogInterface dialog, int whichButton) {  
                      dialog.dismiss();  
                      /**  
                       * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方  
                       * 文档，you_sdk_path/docs/guide/topics/media/camera.html  
                       * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为  
                       * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正  
                       */  
                      Intent intent = new Intent(  
                              MediaStore.ACTION_IMAGE_CAPTURE);  
                      //下面这句指定调用相机拍照后的照片存储的路径  
                      intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri  
                              .fromFile(new File(fileHelper.appFilePath + "pic/",  
                                      "head.jpeg")));  
                      startActivityForResult(intent, 2);  
                  }  
              }).show();  
  }  

  private void initComponent()
  {
    this.head_imv = ((ImageView)findViewById(R.id.head));
    //this.head_imv.setImageBitmap(BitmapHelper.toRoundBitmap(this.header_bitmap));
    this.name_show_tv = ((TextView)findViewById(R.id.nick_name_show));
    this.name_show_tv.setText(this.name);
    this.phone_number_show_tv = ((TextView)findViewById(R.id.phone_number_show));
    this.phone_number_show_tv.setText(this.phone_num);
    this.logout_btn = ((Button)findViewById(R.id.logout_btn));
    this.name_rl = ((RelativeLayout)findViewById(R.id.nick_name_rl));
    this.change_head_tv = ((TextView)findViewById(R.id.changeHead));
    change_head_rl = (RelativeLayout) findViewById(R.id.change_head_rl);
    phone_rl = (RelativeLayout) findViewById(R.id.phone_rl);
    pwd_rl = (RelativeLayout) findViewById(R.id.pwd_rl);    
    
  }

  private void initData()
  {	
    this.name = this.helper.getStringValue("name", "无");
    this.phone_num = this.helper.getStringValue("phone");
    if(new_phone!=null)
    	phone_num = new_phone;
    getUserData();
  }

  private void initEventListener()
  {
    this.name_rl.setOnClickListener(this);
    this.logout_btn.setOnClickListener(this);
    this.change_head_rl.setOnClickListener(this);
    phone_rl.setOnClickListener(this);
    pwd_rl.setOnClickListener(this);
  }

  private void initTitleBar()
  {
	ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
    this.title_bar = this.inflater.inflate(R.layout.account_action_bar, null);
    this.actionBar.setCustomView(this.title_bar, lp);
    this.actionBar.setDisplayShowHomeEnabled(false);
    this.actionBar.setDisplayShowTitleEnabled(false);
    this.actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    this.actionBar.setDisplayShowCustomEnabled(true);
  }

 
    
  /**  
   * 裁剪图片方法实现  
   * @param uri  
   */ 
  public void startPhotoZoom(Uri uri) {  
      /*  
       * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页  
       * yourself_sdk_path/docs/reference/android/content/Intent.html  
       * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,  
       * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么  
       * 制做的了...吼吼  
       */ 
      Intent intent = new Intent("com.android.camera.action.CROP");  
      intent.setDataAndType(uri, "image/*");  
      //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪  
      intent.putExtra("crop", "true");  
      // aspectX aspectY 是宽高的比例  
      intent.putExtra("aspectX", 1);  
      intent.putExtra("aspectY", 1);  
      // outputX outputY 是裁剪图片宽高  
      intent.putExtra("outputX", 150);  
      intent.putExtra("outputY", 150);  
      intent.putExtra("return-data", true);  
      startActivityForResult(intent, 3);  
  }  
    
  /**  
   * 保存裁剪之后的图片数据  
   * @param picdata  
   */  
  private void setPicToView(Intent picdata) {  
      Bundle extras = picdata.getExtras();  
      if (extras != null) {  
          Bitmap photo = extras.getParcelable("data");    
          this.head_imv.setImageBitmap(BitmapHelper.toRoundBitmap(photo)); 
          /**  
           * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上  
           * 传到服务器，QQ头像上传采用的方法跟这个类似  
           */ 
            
          ByteArrayOutputStream stream = new ByteArrayOutputStream();  
          photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);  
          byte[] b = stream.toByteArray();
          try {
			this.fileHelper.writeSDFile("pic", "head_thumbail.jpeg").write(b);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
          // 将图片流以字符串形式存储下来   
          String tp = new String(Base64Coder.encodeLines(b));
          updateHeader(tp,tp);

      }  
  }  

  /**
 * @param tp
 */
private void updateHeader(String small, String big) {
	
	RequestParams params = new RequestParams(); 
	params.add("dataString", big);
    params.add("smallData", small);
	YJRHttpClient.post(context,"/user/updateAvatar", params, new JsonHttpResponseHandler(){
		 @Override  
            public void onSuccess(JSONObject data) {  
             	jsonInfo = data;
             	try {
					if(jsonInfo.getInt("result") == 1){
						YJRHttpClient.setCookie(context); 
						Toast.makeText(context, "上传成功", Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }  
	});
	
}

public void onClick(View view)
  {
	Intent intent;
    switch (view.getId())
    {
    case R.id.nick_name_rl:
    	intent = new Intent(AccountActivity.this, NameEditActivity.class);
    	intent.putExtra("name", name);
    	startActivityForResult(intent, 4);
      break;
    case R.id.logout_btn:
      logout();
      break;
    case R.id.change_head_rl:
      ShowPickDialog();
      break;
    case R.id.phone_rl:
    	intent = new Intent(AccountActivity.this, ChangePhoneActivity.class);
    	startActivity(intent);
    	break;
    case R.id.pwd_rl:
    	intent = new Intent(AccountActivity.this, SetPwdActivity.class);
    	startActivity(intent);
    	break;
    default:
    	  break;
    }
  }

private void logout(){
		YJRHttpClient.post(context,"/user/logout", null, new JsonHttpResponseHandler(){
			 @Override  
	            public void onSuccess(JSONObject data) {  
	             	jsonInfo = data;
	             	try {
						if(jsonInfo.getInt("result") == 1){
							Toast.makeText(context, "注销成功", Toast.LENGTH_LONG).show();
							helper.putString("password", "0");
						}else{
							Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }  
		});
	}
  
protected void onCreate(Bundle paramBundle)
  {
    super.onCreate(paramBundle);
    setContentView(R.layout.activity_account);
    options = new DisplayImageOptions.Builder()
	.showImageOnLoading(R.drawable.me_jobinfo)
	.showImageForEmptyUri(R.drawable.me_appointment)
	.showImageOnFail(R.drawable.head)
	.cacheInMemory(true)
	.cacheOnDisc(true)
	.considerExifParams(true)
	.displayer(new RoundedBitmapDisplayer(100))//是否设置为圆角，弧度为多少  
	.bitmapConfig(Bitmap.Config.RGB_565)
	.build();
    this.inflater = getLayoutInflater();
    this.actionBar = getSupportActionBar();
    this.context = this;
    this.mHandler = new Handler();
    this.helper = new SharedPreferencesHelper(this.context);
    this.fileHelper = new FileHelper(this.context);
    Intent intent = getIntent();
    new_phone = intent.getStringExtra("new_phone");
    initData();
    initTitleBar();
    initComponent();
    initEventListener();
  }
   
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
      switch (requestCode) {
      case 4:
    	  Toast.makeText(context, "name change", Toast.LENGTH_SHORT).show();
    	  if(data!=null){
    		  name = data.getStringExtra("name");
        	  name_show_tv.setText(name);
    	  }
    	  break;
      // 如果是直接从相册获取  
      case 1:  
          startPhotoZoom(data.getData());  
          break;  
      // 如果是调用相机拍照时  
      case 2:  
          File temp = new File(fileHelper.appFilePath
                  + "pic/head.jpeg");  
          startPhotoZoom(Uri.fromFile(temp));  
          break;  
      // 取得裁剪后的图片  
      case 3:  
          /**  
           * 非空判断大家一定要验证，如果不验证的话，  
           * 在剪裁之后如果发现不满意，要重新裁剪，丢弃  
           * 当前功能时，会报NullException，小马只  
           * 在这个地方加下，大家可以根据不同情况在合适的  
           * 地方做判断处理类似情况  
           *   
           */ 
          if(data != null){  
              setPicToView(data);  
          }  
          break;  
      default:  
          break;  

      }  
      super.onActivityResult(requestCode, resultCode, data);  
  }  

public void getUserData(){
	RequestParams params = new RequestParams(); 
	YJRHttpClient.post(context,"/user/refreshUser.action", params, new JsonHttpResponseHandler(){
		 @Override  
            public void onSuccess(JSONObject data) {  
             	try {
					if(data.getInt("result") == 1){
						YJRHttpClient.setCookie(context); 
						Toast.makeText(context, "获取用户信息成功", Toast.LENGTH_SHORT).show();
						JSONObject userData = data.getJSONObject("response");
						YJRApplication.userData = userData;
						name = userData.getString("name");
						phone_num = userData.getString("phone");
						head_path = userData.getString("avatar");
						setComponent();
						//TODO 将用户信息存储在本地
							
					}else{
						Toast.makeText(context, data.getString("info"), Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }  
	});
}

/**
 * 
 */
protected void setComponent() {
	// TODO Auto-generated method stub
	name_show_tv.setText(name);
	phone_number_show_tv.setText(phone_num);
    imageLoader.displayImage("http://115.28.222.1/yijiaren/pics/avatar/"+head_path, head_imv, options);

}
}